// import { allSettled } from "core-js/fn/promise"
// import { Level } from "chalk";
import moment from "moment"
/**val选中的值
oldCenters备用2为数组
vmcenterArray绑定的数组
centerOptions选项合集
allSelect所有选项对应的值
value单选框对应的值
subobj数据格式是否是this.vmcenterArray.subobj这样的格式
 */
export function allSelectFun(
    _this,
    val,
    oldCenters,
    vmcenterArray,
    centerSelectList,
    allSelect,
    value = "value",
    subObj = null
) {
    //全选逻辑
    let allValues = [];
    for (let item of _this[centerSelectList]) {
        if (value !== null) {
            allValues.push(item[value]);
        } else {
            allValues.push(item);
        }
    }
    const oldVal = _this[oldCenters].length === 1 ? [] : _this[oldCenters][1];
    if (val.includes(allSelect)) {
        if (subObj) {
            _this[vmcenterArray][subObj] = allValues;
        } else {
            _this[vmcenterArray] = allValues
        }
    }
    if (oldVal.includes(allSelect) && !val.includes(allSelect)) {
        if (subObj) {
            _this[vmcenterArray][subObj] = [];
        } else {
            _this[vmcenterArray] = []
        }
    }
    if (oldVal.includes(allSelect) && val.includes(allSelect)) {
        const index = val.indexOf(allSelect);
        val.splice(index, 1);
        if (subObj) {
            _this[vmcenterArray][subObj] = val;
        } else {
            _this[vmcenterArray] = val;
        }
    }
    if (!oldVal.includes(allSelect) && !val.includes(allSelect)) {
        if (val.length === allValues.length - 1) {
            if (subObj) {
                _this[vmcenterArray][subObj] = [allSelect].concat(val);
            } else {
                _this[vmcenterArray] = [allSelect].concat(val);
            }
        }

    }
    if (subObj) {
        _this[oldCenters][1] = _this[vmcenterArray][subObj];
    } else {
        _this[oldCenters][1] = _this[vmcenterArray];
    }
}

//深拷贝
export function deepCopy(obj) {
    const result = Array.isArray(obj) ? [] : {}
    for (const key in obj) {
        if (obj.hasOwnProperty(key))
            if (typeof obj[key] === 'object' && obj[key] !== null) {
                result[key] = deepCopy(obj[key])
            } else {
                result[key] = obj[key]
            }
    }
    return result;
}

//数组去重
export function filterDuplicateObjArray(arr, param) {
    if (Array.isArray(arr)) {
        let temp = [];
        const newArr = arr.reduce((acc, cur) => {
            if (temp.indexOf(cur[param]) === -1) {
                temp.push(cur[param]);
                acc.push(cur)
                return acc;
            }
            return acc;
        }, []);
        const isDuplicate = newArr.length !== arr.length;
        return { newArr, isDuplicate }
    }
}


//级联回显数据
export function getSelectValueList(key, treeData) {
    let arr = [];
    let resArr = [];
    let level = 0;
    function findtree(children, levelN) {
        for (let index = 0; index < children.length; index++) {
            level = levelN
            arr[levelN] = children[index].value
            if (children[index].value == key) {
                resArr = arr.slice(0, levelN + 1)
                break;
            } else {
                if (children[index].children) {
                    level++
                    findtree(children[index].children, level)
                }
            }
        }
        return resArr
    }
    return findtree(treeData, level)
}
//两数相除
export function diver(a, b) {
    var c = 1
    var d = 1
    var e = 0
    var f = 0
    try {
        e = a.toString().split('.')[1].length
    } catch (g) { }
    try {
        f = b.toString().split('.')[1].length
    } catch (g) { }
    return c = Number(a.toString().replace('.', '')), d = Number(b.toString().replace('.', '')), mul(c / d, Math.pow(10, f - e))

}
//两数相乘
export function mul(a, b) {
    var c = 1
    var d = a.toString()
    var e = b.toString()
    try {
        c += d.split('.')[1].length
    } catch (f) { }
    try {
        c += e.split('.')[1].length
    } catch (f) { }
    return Number(d.replace('.', '')) * Number(e.replace('.', '')) / Math.pow(10, c)

}
//两数相减
export function sub(a, b) {
    var c = 0
    var d = 0
    var e = 1
    try {
        c = a.toString().split('.')[1].length
    } catch (f) { }
    try {
        d = b.toString().split('.')[1].length
    } catch (f) { }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) - mul(b, e)) / e
}
//两数相加
export function add(a, b) {
    var c = 0
    var d = 0
    var e = 1
    try {
        c = a.toString().split('.')[1].length
    } catch (f) { }
    try {
        d = b.toString().split('.')[1].length
    } catch (f) { }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e
}


//报表视图弹出框区分中心，部门，小组
export function getTableType(centerParam, deptParam, groupParam) {
    let tableType = "";
    if (centerParam.length > 0 && deptParam.length == 0 && groupParam.length == 0) {
        tableType = "center"
    } else if (centerParam.length > 0 && deptParam.length > 0 && groupParam.length == 0) {
        tableType = "dept"
    } else if (centerParam.length > 0 && groupParam.length > 0) {
        tableType = "group"
    }
    return tableType
}

//notice弹出框，点击多次弹出，该方法删除前一个弹出，只保留每次弹出一个框
export function deleteNotice() {
    let dom = document.getElementsByClassName("el-notification");
    if (dom.length == 1 || dom.length > 1) {
        dom[0].remove();
    }
}

export function reWriteData(dateSearch, monthDay = "0", weekDay = "0") {
    //当选择当月时，返回月初到当前日期
    if (dateSearch.time == "month") {
        let selectYear = new Date(dateSearch.chooseDate).getFullYear();
        let selectMonth = new Date(dateSearch.chooseDate).getMonth() + 1;
        let nowYear = new Date().getFullYear();
        let nowMonth = new Date().getMonth() + 1;
        if (selectYear == nowYear && selectMonth == nowMonth) {
            dateSearch.searchDate[1] = moment().format("YYYY-MM-DD");
            //monthDay设置为当前的前一天
            if (monthDay == "-1") {
                dateSearch.searchDate[1] = moment(new Date().getTime() - 3600 * 24 * 1000 * 1).format(YYYY - MM - DD)
            }
        }
    }
    //当选择的是本周的时候，则返回周一至当前日期
    if (dateSearch.time == "week") {
        function getWeekNum(dt) {
            let d1 = new Date(dt);
            let d2 = new Date(dt);
            d2.setMonth(0);
            d2.setDate(1);
            let rq = d1 - d2;
            let days = Math.ceil(rq / (24 * 60 * 60 * 1000));
            let num = Math.ceil(days / 7);
            return num + 1;
        }
        let ww = getWeekNum(dateSearch.chooseDate);
        let nowWeek = getWeekNum(moment().format("YYYY-MM-DD"));
        if (ww == nowWeek) {
            dateSearch.searchDate[1] = moment().format("YYYY-MM-DD")
            //weekDay设置为当前的前一天
            if (weekDay == "-1") {
                dateSearch.searchDate[1] = moment(new Date().getTime() - 3600 * 24 * 1000 * 1).format("YYYY-MM-DD")
            }
        }
    }
}


//去掉小数点后多余的0，50.20->50.2
export function cutZero(old) {
    var newstr = old;
    let leng = old.length - old.indexOf(".") - 1;
    if (old.indexOf(".") > -1) {
        for (let i = leng; i > 0; i++) {
            if (newstr.lastIndexOf("0") > -1 && newstr.substr(newstr.length - 1, 1) == 0) {
                let k = newstr.lastIndexOf("0");
                if (newstr.charAt(k - 1) == ".") {
                    return newstr.substring(0, k - 1);

                } else {
                    newstr = newstr.substring(0, k);
                }
            } else {
                return newstr
            }
        }
    }
    return old
}

//判断是否全选
export function filterAllSelect(list) {
    let flag = list.some((v) => v == "ALL_SELECT");
    return flag
}

//toFixed四舍五入不准确问题
export function toFixedRound(number, fractionDigits) {
    return Math.round(number * Math.pow(10, fractionDigits)) / Math.pow(10, fractionDigits)
}

//选择框，过滤“全选”两个字 query搜索输入的关键字 label 选择框绑定的值 selectOptions选择框数据，selectOptionsCopy选择框深拷贝
export function filterMethod(query, label = "label", selectOptions, selectOptionsCopy) {
    if (query) {
        selectOptions = selectOptionsCopy.filter((item) => {
            if (item[label]) {
                return ((item[label].indexOf(query) > -1 || item[label].toUpperCase().indexOf(query.toUpperCase()) > -1) && item[label] !== "全选")
            }
        });
    } else {
        selectOptions = selectOptionsCopy
    }
    return { selectOptions }
}

//參數val搜索的关键字   data搜索数据的集合 juge是data里面的搜索对应值
export function fliterTreeDataSearch(val = "", data = this.personJobLevelOptions, juge = "label", children = "children") {
    //递归遍历结果，查出是否展示
    function tree(treeData) {
        treeData.forEach((elm) => {
            elm.isShow = false
            // 模糊搜索
            // if(elm[juge]&&elm[juge].toString().search(val)>1){
            //     elm.isShow=true
            // }
            //精确搜索
            if (elm[juge] && elm[juge].toString() == val) {
                elm.isShow = true
            }
            if (elm[children]) {
                tree(elm[children])
            }
        });
    }
    tree(data)

    //过滤数据
    function treeFilter(treeData) {
        const elm = []
        for (let i = 0; i < treeData.length; i++) {
            const item = JSON.parse(JSON.stringify(treeData[i]));
            if (treeData[i].isShow) {
                elm.push(item);
                if (treeData[i][children] && treeData[i][children].length) {
                    item[children] = treeFilter(treeData[i][children]);
                    if (!item[children].length) {
                        delete item[children]
                    }
                }
            } else if (treeData[i][children] && treeData[i][children].length) {
                elm.push.apply(elm, treeFilter(treeData[i][children]))
            }
        }
        return elm
    }
    const a = treeFilter(data)
    return a
}

//处理返回结果为null 转换成 "-"
export function transformNull(data, defaultStr = "-") {
    if (typeof data != "object" || data == "null") {
        if (data == null || data == "null" || data == "" || !data) {
            return defaultStr
        } else {
            return data
        }
    }
    for (const v in data) {
        if (data[v] == null || data[v] == "null" || data[v] == "" || !data[v]) {
            data[v] = defaultStr;
        }
        if (typeof data[v] == "object") {
            transformNull(data[v])
        }
    }
    return data
}

//给centerId deptid groupid赋值
export function resetOrginzationId(_that, role, organization) {
    //先还原成最初的值，然后按照选中的对应的角色赋值新的id
    _that.$store.dispatch("user/changeCenterId", _that.$store.state.user.orginIds.centerId);
    _that.$store.dispatch("user/changeDeptId", _that.$store.state.user.orginIds.deptId);
    _that.$store.dispatch("user/changeGroupId", _that.$store.state.user.orginIds.groupId);
    if (role == "general") {

    } else if (role == "center") {
        _that.$store.dispatch("user/changeCenterId", organization)
    } else if (role == "secondary") {
        _that.$store.dispatch("user/changeDeptId", organization)
    } else if (role == "team") {
        _that.$store.dispatch("user/changeGroupId", organization)
    }
}